<?php
/**
*
* @package acp
* @version $Id: acp_express_ads.php,v 1.002 2008/03/01 04:46:00 nedka Exp $
* @copyright (c) 2008 nedka (Nguyen Dang Khoa)
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
* @ignore
*/
if (!defined('IN_PHPBB'))
{
	exit;
}

/**
* @package acp
*/
class acp_express_ads
{
	var $u_action;

	function main($id, $mode)
	{
		global $db, $user, $auth, $template, $cache;
		global $config, $phpbb_root_path, $phpbb_admin_path, $phpEx;

		$user->add_lang('mods/express');

		// Set up general vars
		$action = request_var('action', '');
		$action = (isset($_POST['add'])) ? 'add' : $action;
		$action = (isset($_POST['edit'])) ? 'edit' : $action;
		$ads_id = request_var('id', 0);

		$this->tpl_name = 'acp_express_ads';
		$this->page_title = 'ACP_EXPRESS_ADS';

		// Clear some arrays
		$_images = array();
		$notice = '';

		// Grab file list of advertising images
		if ($action == 'edit' || $action == 'add')
		{
			$imglist = filelist($phpbb_root_path . $config['express_ads_path'], '');

			foreach ($imglist as $path => $img_ary)
			{
				foreach ($img_ary as $img)
				{
					$img_size = getimagesize($phpbb_root_path . $config['express_ads_path'] . '/' . $path . $img);

					if (!$img_size[0] || !$img_size[1] || strlen($img) > 255)
					{
						continue;
					}

					$_images[$path . $img]['file'] = $path . $img;
					$_images[$path . $img]['width'] = $img_size[0];
					$_images[$path . $img]['height'] = $img_size[1];
				}
			}
			unset($imglist);

/*			if ($dir = @opendir($phpbb_root_path . $config['express_ads_path']))
			{
				while (($file = readdir($dir)) !== false)
				{
					if (is_file($phpbb_root_path . $config['express_ads_path'] . '/' . $file) && preg_match('#\.pak$#i', $file))
					{
						$_paks[] = $file;
					}
				}
				closedir($dir);
			}*/
		}

		// What shall we do today? Oops, I believe that's trademarked ...
		switch ($action)
		{
			case 'edit':
				unset($_images);
				$_images = array();

			// no break;

			case 'add':

				$ads = $default_row = array();
				$ads_options = $order_list = $add_order_list = '';

				if ($action == 'add')
				{
					$sql = 'SELECT *
						FROM ' . EXPRESS_ADS_TABLE . '
						ORDER BY ads_order';
					$result = $db->sql_query($sql);

					while ($row = $db->sql_fetchrow($result))
					{
						if (empty($ads[$row['ads_image']]))
						{
							$ads[$row['ads_image']] = $row;
						}
					}
					$db->sql_freeresult($result);

					if (sizeof($ads))
					{
						foreach ($ads as $row)
						{
							$selected = false;

							if (!$ads_options)
							{
								$selected = true;
								$default_row = $row;
							}
							$ads_options .= '<option value="' . $row['ads_image'] . '"' . (($selected) ? ' selected="selected"' : '') . '>' . $row['ads_image'] . '</option>';

							$template->assign_block_vars('ads', array(
								'IMAGE'		=> addslashes($row['ads_image']),
								'TEXT'		=> addslashes($row['ads_title']),
								'TEXT'		=> addslashes($row['ads_text']),
								'URL'		=> addslashes($row['ads_url']),// NEN DUNG htmlspecialchars.... COI LAI
								'WIDTH'		=> $row['ads_width'],
								'HEIGHT'	=> $row['ads_height'],
								'ORDER'		=> $row['ads_order'] + 1,
							));
						}
					}
				}

				$sql = 'SELECT *
					FROM ' . EXPRESS_ADS_TABLE . '
					ORDER BY ads_order ' . (($ads_id || $action == 'add') ? 'DESC' : 'ASC');
				$result = $db->sql_query($sql);
				
				$data = array();
				$after = false;
				$display = 0;
				$order_lists = array('', '');
				$add_order_lists = array('', '');
				$display_count = 0;

				while ($row = $db->sql_fetchrow($result))
				{
					if ($action == 'add')
					{
						unset($_images[$row['ads_image']]);
					}

					if ($row['ads_id'] == $ads_id)
					{
						$after = true;
						$display = $row['ads_display'];
						$data[$row['ads_image']] = $row;
					}
					else
					{
						if ($action == 'edit' && !$ads_id)
						{
							$data[$row['ads_image']] = $row;
						}

						$selected = '';
						if (!empty($after))
						{
							$selected = ' selected="selected"';
							$after = false;
						}

						if ($row['ads_display'])
						{
							$display_count++;
						}

						$after_txt = $row['ads_image'];
						$order_lists[$row['ads_display']] = '<option value="' . ($row['ads_order'] + 1) . '"' . $selected . '>' . sprintf($user->lang['AFTER_ADS'], ' -&gt; ' . $after_txt) . '</option>' . $order_lists[$row['ads_display']];

						if (!empty($default_row))
						{
							$add_order_lists[$row['ads_display']] = '<option value="' . ($row['ads_order'] + 1) . '"' . (($row['ads_id'] == $default_row['ads_id']) ? ' selected="selected"' : '') . '>' . sprintf($user->lang['AFTER_ADS'], ' -&gt; ' . $after_txt) . '</option>' . $add_order_lists[$row['ads_display']];
						}
					}
				}
				$db->sql_freeresult($result);

				$order_list = '<option value="1"' . ((!isset($after)) ? ' selected="selected"' : '') . '>' . $user->lang['FIRST'] . '</option>';
				$add_order_list = '<option value="1">' . $user->lang['FIRST'] . '</option>';

				if ($action == 'add')
				{
					$data = $_images;
				}

				$colspan = '6';
				$colspan += ($ads_id) ? 1 : 0;
				$colspan += ($action == 'add') ? 2 : 0;

				$template->assign_vars(array(
					'S_EDIT'	=> true,
					'S_ADD'		=> ($action == 'add') ? true : false,

					'S_ORDER_LIST_DISPLAY'			=> $order_list . $order_lists[1],
					'S_ORDER_LIST_UNDISPLAY'		=> $order_list . $order_lists[0],
					'S_ORDER_LIST_DISPLAY_COUNT'	=> $display_count + 1,

// CHUYEN QUA TEMPLATE NEN DUNG TRUC TIEP....
					'L_CONFIG'		=> $user->lang['ADS_CONFIG'],
					'L_URL'			=> $user->lang['ADS_IMAGE'],
					'L_LOCATION'	=> $user->lang['ADS_LOCATION'],
					'L_WIDTH'		=> $user->lang['ADS_WIDTH'],
					'L_HEIGHT'		=> $user->lang['ADS_HEIGHT'],
					'L_ORDER'		=> $user->lang['ADS_ORDER'],
					'L_NO_ADS'		=> $user->lang['NO_ADS_' . strtoupper($action)],// NGOAI LE???
// CHUYEN QUA TEMPLATE NEN DUNG TRUC TIEP....

					'COLSPAN'	=> $colspan,
					'ID'		=> $ads_id,

					'U_BACK'	=> $this->u_action,
					'U_ACTION'	=> $this->u_action . '&amp;action=' . (($action == 'add') ? 'create' : 'modify'),
				));

				foreach ($data as $img => $img_row)
				{
					$template->assign_block_vars('items', array(
						'IMG'		=> $img,
						'A_IMG'		=> addslashes($img),
						'IMG_SRC'	=> $phpbb_root_path . $config['express_ads_path'] . '/' . $img,

						'TITLE'	=> (isset($img_row['ads_title'])) ? $img_row['ads_title'] : '',
						'URL'	=> (isset($img_row['ads_url'])) ? $img_row['ads_url'] : '',
						'TEXT'	=> (isset($img_row['ads_text'])) ? $img_row['ads_text'] : '',

						'S_ID'				=> (isset($img_row['ads_id'])) ? true : false,
						'ID'				=> (isset($img_row['ads_id'])) ? $img_row['ads_id'] : 0,
						'WIDTH'				=> (!empty($img_row['ads_width'])) ? $img_row['ads_width'] : $img_row['width'],
						'HEIGHT'			=> (!empty($img_row['ads_height'])) ? $img_row['ads_height'] : $img_row['height'],
						'DISPLAY_CHECKED'	=> (!empty($img_row['ads_display']) || $action == 'add') ? ' checked="checked"' : '',
					));
				}

				// Ok, another row for adding an addition text for a pre-existing image...
				if ($action == 'add' && sizeof($ads))
				{
					$template->assign_vars(array(						
						'IMG_SRC'			=> $phpbb_root_path . $config['express_ads_path'] . '/' . $default_row['ads_image'],
						'IMG_PATH'			=> $config['express_ads_path'],
						'PHPBB_ROOT_PATH'	=> $phpbb_root_path,

						'TITLE'		=> $default_row['ads_title'],
						'URL'		=> $default_row['ads_image'],
						'TEXT'		=> $default_row['ads_text'],
						'WIDTH'		=> $default_row['ads_width'],
						'HEIGHT'	=> $default_row['ads_height'],

						'S_ADD_INFO'					=> true,
						'S_IMG_OPTIONS'					=> $ads_options,
						'S_ADD_ORDER_LIST_DISPLAY'		=> $add_order_list . $add_order_lists[1],
						'S_ADD_ORDER_LIST_UNDISPLAY'	=> $add_order_list . $add_order_lists[0],
					));
				}

				return;

			break;

			case 'create':
			case 'modify':

				// Get items to create/modify
				$images = (isset($_POST['image'])) ? array_keys(request_var('image', array('' => 0))) : array();

				// Now really get the items
				$image_id = (isset($_POST['id'])) ? request_var('id', array('' => 0)) : array();
				$image_order = (isset($_POST['order'])) ? request_var('order', array('' => 0)) : array();
				$image_width = (isset($_POST['width'])) ? request_var('width', array('' => 0)) : array();
				$image_height = (isset($_POST['height'])) ? request_var('height', array('' => 0)) : array();
				$image_add = (isset($_POST['add_img'])) ? request_var('add_img', array('' => 0)) : array();
				$image_title = utf8_normalize_nfc(request_var('title', array('' => ''), true));
				$image_url = utf8_normalize_nfc(request_var('url', array('' => ''), true));
				$image_text = utf8_normalize_nfc(request_var('text', array('' => ''), true));
				$image_display = (isset($_POST['display'])) ? request_var('display', array('' => 0)) : array();

				// Ok, add the relevant bits if we are adding new information to existing advertisements...
				if (!empty($_POST['add_additional_info']))
				{
					$add_image = request_var('add_image', '');
					$add_title = utf8_normalize_nfc(request_var('add_title', '', true));
					$add_url = utf8_normalize_nfc(request_var('add_url', '', true));
					$add_text = utf8_normalize_nfc(request_var('add_text', '', true));

					if ($add_image && $add_title && $add_url && $add_text)
					{
						$images[] = $add_image;
						$image_add[$add_image] = true;

						$image_title[$add_image] = $add_title;
						$image_url[$add_image] = $add_url;
						$image_text[$add_image] = $add_text;
						$image_width[$add_image] = request_var('add_width', 0);
						$image_height[$add_image] = request_var('add_height', 0);

						if (!empty($_POST['add_display']))
						{
							$image_display[$add_image] = 1;
						}

						$image_order[$add_image] = request_var('add_order', 0);
					}
				}

				$ads_updated = 0;
				foreach ($images as $image)
				{
					if (($image_title[$image] == '' || $image_url[$image] == '' || $image_text[$image] == '') ||
						($action == 'create' && !isset($image_add[$image])))
					{
					}
					else
					{
						if ($image_width[$image] == 0 || $image_height[$image] == 0)
						{
							$img_size = getimagesize($phpbb_root_path . $config['express_ads_path'] . '/' . $image);
							$image_width[$image] = $img_size[0];
							$image_height[$image] = $img_size[1];
						}

						$img_sql = array(
							'ads_image'		=> $image,
							'ads_title'		=> $image_title[$image],
							'ads_url'		=> $image_url[$image],
							'ads_text'		=> $image_text[$image],
							'ads_width'		=> $image_width[$image],
							'ads_height'	=> $image_height[$image],
							'ads_display'	=> (isset($image_display[$image])) ? 1 : 0,
						);

						// Image_order holds the 'new' order value
						if (!empty($image_order[$image]))
						{
							$img_sql = array_merge($img_sql, array(
								'ads_order'	=>	$image_order[$image],
							));

							// Since we always add 'after' an item, we just need to increase all following + the current by one
							$sql = 'UPDATE ' . EXPRESS_ADS_TABLE . " SET ads_order = ads_order + 1 WHERE ads_order >= {$image_order[$image]}";
							$db->sql_query($sql);

							// If we adjust the order, we need to adjust all other orders too - they became inaccurate...
							foreach ($image_order as $_image => $_order)
							{
								if ($_image == $image)
								{
									continue;
								}

								if ($_order >= $image_order[$image])
								{
									$image_order[$_image]++;
								}
							}
						}

						if ($action == 'modify'  && !empty($image_id[$image]))
						{
							$sql = 'UPDATE ' . EXPRESS_ADS_TABLE . " SET " . $db->sql_build_array('UPDATE', $img_sql) . " WHERE ads_id = " . $image_id[$image];
							$db->sql_query($sql);

							$ads_updated++;
						}
						else if ($action !== 'modify')
						{
							$sql = 'INSERT INTO ' . EXPRESS_ADS_TABLE . $db->sql_build_array('INSERT', $img_sql);
							$db->sql_query($sql);

							$ads_updated++;
						}
 					}
				}

				$cache->destroy('_ads');
				$cache->destroy('sql', EXPRESS_ADS_TABLE);

				$level = E_USER_NOTICE;

				switch ($ads_updated)
				{
					case 0:
						$suc_lang = "ADS_NONE";
						$level = E_USER_WARNING;
					break;

					case 1:
						$suc_lang = "ADS_ONE";
					break;

					default:
						$suc_lang = "ADS";
					break;
				}

				if ($action == 'modify')
				{
					trigger_error($user->lang[$suc_lang . '_EDITED'] . adm_back_link($this->u_action), $level);
				}
				else
				{
					trigger_error($user->lang[$suc_lang . '_ADDED'] . adm_back_link($this->u_action), $level);
				}

			break;

			case 'delete':

				if (confirm_box(true))
				{
					$sql = 'DELETE FROM ' . EXPRESS_ADS_TABLE . " WHERE ads_id = $ads_id";
					$db->sql_query($sql);

					$notice = $user->lang['ADS_DELETED'];

					$cache->destroy('_ads');
					$cache->destroy('sql', EXPRESS_ADS_TABLE);
				}
				else
				{
					confirm_box(false, $user->lang['CONFIRM_OPERATION'], build_hidden_fields(array(
						'i'			=> $id,
						'mode'		=> $mode,
						'id'		=> $ads_id,
						'action'	=> 'delete',
					)));
				}

			break;

			case 'move_up':
			case 'move_down':

				// Get current order id...
				$sql = 'SELECT ads_order as current_order
					FROM ' . EXPRESS_ADS_TABLE . "
					WHERE ads_id = $ads_id";
				$result = $db->sql_query($sql);
				$current_order = (int) $db->sql_fetchfield('current_order');
				$db->sql_freeresult($result);

				if ($current_order == 0 && $action == 'move_up')
				{
					break;
				}

				// on move_down, switch position with next order_id...
				// on move_up, switch position with previous order_id...
				$switch_order_id = ($action == 'move_down') ? $current_order + 1 : $current_order - 1;

				// Update order values
				$sql = 'UPDATE ' . EXPRESS_ADS_TABLE . "
					SET ads_order = $current_order
					WHERE ads_order = $switch_order_id
						AND ads_id <> $ads_id";
				$db->sql_query($sql);

				// Only update the other entry too if the previous entry got updated
				if ($db->sql_affectedrows())
				{
					$sql = 'UPDATE ' . EXPRESS_ADS_TABLE . "
						SET ads_order = $switch_order_id
						WHERE ads_order = $current_order
							AND ads_id = $ads_id";
					$db->sql_query($sql);
				}

				$cache->destroy('_ads');
				$cache->destroy('sql', EXPRESS_ADS_TABLE);

			break;
		}

		// By default, check that image_order is valid and fix it if necessary
		$sql = 'SELECT ads_id AS order_id, ads_order AS fields_order
			FROM ' . EXPRESS_ADS_TABLE . '
			ORDER BY ads_display DESC, ads_order';
		$result = $db->sql_query($sql);

		if ($row = $db->sql_fetchrow($result))
		{
			$order = 0;
			do
			{
				++$order;
				if ($row['fields_order'] != $order)
				{
					$db->sql_query('UPDATE ' . EXPRESS_ADS_TABLE . "
						SET ads_order = $order
						WHERE ads_id = " . $row['order_id']);
				}
			}
			while ($row = $db->sql_fetchrow($result));
		}
		$db->sql_freeresult($result);

		$template->assign_vars(array(
// KIEM TRA DUNG TRUC TIEP TREN TEMPLATE....
			'L_NOT_DISPLAYED'	=> $user->lang['ADS_NOT_DISPLAYED'],
			'L_ADS_ADD'			=> $user->lang['ADD_ADS'],
			'L_ADS_EDIT'		=> $user->lang['EDIT_ADS'],
// KIEM TRA DUNG TRUC TIEP TREN TEMPLATE....

			'NOTICE'	=> $notice,
			'COLSPAN'	=> 4,

			'U_ACTION'	=> $this->u_action,
		));

		$spacer = false;

		$sql = 'SELECT *
			FROM ' . EXPRESS_ADS_TABLE . '
			ORDER BY ads_order ASC';
		$result = $db->sql_query($sql);

		while ($row = $db->sql_fetchrow($result))
		{
			$alt_text = $row['ads_title'];

			$template->assign_block_vars('items', array(
				'IMG_SRC'	=> $phpbb_root_path . $config['express_ads_path'] . '/' . $row['ads_image'],

				'ALT_TEXT'	=> $alt_text,
				'WIDTH'		=> $row['ads_width'],
				'HEIGHT'	=> $row['ads_height'],
				'TITLE'		=> (isset($row['ads_title'])) ? $row['ads_title'] : '',
				'URL'		=> (isset($row['ads_url'])) ? $row['ads_url'] : '',
				'TEXT'		=> (isset($row['ads_text'])) ? $row['ads_text'] : '',
				'CLICKS'	=> $row['ads_clicks'],

				'U_EDIT'		=> $this->u_action . '&amp;action=edit&amp;id=' . $row['ads_id'],
				'U_DELETE'		=> $this->u_action . '&amp;action=delete&amp;id=' . $row['ads_id'],
				'U_MOVE_UP'		=> $this->u_action . '&amp;action=move_up&amp;id=' . $row['ads_id'],
				'U_MOVE_DOWN'	=> $this->u_action . '&amp;action=move_down&amp;id=' . $row['ads_id'],

				'S_SPACER'	=> (!$spacer && !$row['ads_display']) ? true : false,
			));

			if (!$spacer && !$row['ads_display'])
			{
				$spacer = true;
			}
		}
		$db->sql_freeresult($result);
	}
}

?>